import { data as globalData } from "./globalData.mts";

export function logger(
  type: "info" | "warn" | "error",
  ...data: unknown[]
): void;
export function logger(
  type: "data",
  data: unknown[] | Record<string, unknown>,
): void;
export function logger(
  type: "color",
  info: string,
  color: string,
  ...data: unknown[]
): void;
export function logger(type: "count", label: string): void;
export function logger(
  type: "info" | "warn" | "error" | "data" | "color" | "count",
  ...data: unknown[]
): void {
  if (globalData.alertLog) {
    alert(
      JSON.stringify(
        {
          type: type,
          data: data,
        },
        null,
        2,
      ),
    );
  }
  switch (type) {
    case "info": {
      console.info(...data);
      break;
    }
    case "warn": {
      console.warn(...data);
      break;
    }
    case "error": {
      console.error(...data);
      break;
    }
    case "data": {
      console.table(data[0]);
      break;
    }
    case "color": {
      console.log(
        `%c ${data[0] as string}`,
        `display: inline-block; color: white; background: ${data[1] as string}; border-radius: .75em; padding: 2px 5px`,
        ...data.splice(2),
      );
      break;
    }
    case "count": {
      console.count(data[0] as string);
      break;
    }
    default: {
      break;
    }
  }
}

export function speed(item: string, mark: "start" | "end") {
  try {
    if (mark === "start") {
      logger("color", `${item} 开始`, "purple");
      performance.mark(item + mark);
    } else {
      if (performance.getEntriesByName(item + "start", "mark").length > 0) {
        performance.mark(item + mark);
        performance.measure(item, item + "start", item + "end");
        logger(
          "color",
          `${item} 结束`,
          "purple",
          performance.getEntriesByName(item)[0].duration,
        );
        performance.clearMarks(item + "start");
        performance.clearMarks(item + "end");
        performance.clearMeasures(item);
      }
    }
  } catch (error) {
    logger(
      "error",
      typeof error == "string" ? error : (error as ErrorEvent).message,
    );
  }
}

export function countLength(
  object: Record<string, string>,
): Record<keyof typeof object, number> {
  const count: Record<keyof typeof object, number> = {};
  for (const k of Object.keys(object)) {
    count[k] = object[k].length;
  }
  return count;
}
